import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { retry } from 'rxjs/operators';

declare var form: any;
declare var base: any;
declare var security: any;

@Component({
  templateUrl: './data.metadata.html'
})
export class DataMetadataComponent implements OnInit {

  fs: any = null;
  regfs: any = null;
  metadataDic: any = null;
  dataTypeDic: any = null;
  local = true;
  selectNode: any;

  constructor(
    private http: HttpClient) {
    // 注册表单
    this.fs = new form.FormSideSimpleService('metadata', {
      keyField: 'id',
      randomFields: ['id'],
      orderObject: { order: 0 },
      foreignKey: 'mid'
    });
    // 注册导入表单
    this.regfs = new form.FormSimpleService('reg', {
      keyField: 'id',
      orderObject: { order: 0 }
    });
    this.regfs.er = {};
    this.regfs.er.driver = 'com.mysql.jdbc.Driver';
    this.regfs.er.url = 'jdbc:mysql://47.95.220.20:3306/zderp_bms';
    this.regfs.er.username = 'root';
    this.regfs.er.password = '';

    // 初始化字典
    this.metadataDic = new form.DictionaryService('f_metadata_directory');
    this.metadataDic.loadAll();
    this.dataTypeDic = new form.DictionaryService('f_datatype');
  }

  addRow() {
    if (this.selectNode && this.selectNode._isLeaf === true) {
      this.fs.addRow();
    }
  }

  loadDataEx(node: any) {
    if (node._isLeaf === true) {
      this.fs.loadDataEx(node.key);
    } else {
      this.fs.datas = [];
    }
    this.selectNode = node;
  }

  import() {
    if (this.selectNode && this.selectNode._isLeaf === true) {
      this.regfs.openEdit();
    }
  }

  // 获取单个记录
  reg() {
    const mid = this.fs.foreignValue;
    if (!mid) {
      return;
    }

    if (this.local === true) {
      const jwts = security.SecurityService.jwt;
      const url = base.BaseService.getHostUrl() + '/metadata/reg/' + this.regfs.er.tableName + '/' + mid;
      const result = this.http.post<any>(url, '', { headers: new HttpHeaders({ jwt: jwts }) })
        .pipe(retry(1));
      this.regfs.isSaveing = true;
      result.subscribe(
        () => {
          this.regfs.isSaveing = false;
          this.regfs.closeEdit();
          this.fs.resetQueryObject();
          this.fs.loadData(true);
        },
        () => {
          this.regfs.isSaveing = false;
        }
      );
    } else {
      this.regfs.er.mid = mid;
      const jwts = security.SecurityService.jwt;
      const url = base.BaseService.getHostUrl() + '/metadata/reg2';
      const result = this.http.post<any>(url, this.regfs.er, { headers: new HttpHeaders({ jwt: jwts }) })
        .pipe(retry(1));
      this.regfs.isSaveing = true;
      result.subscribe(
        () => {
          this.regfs.isSaveing = false;
          this.regfs.closeEdit();
          this.fs.resetQueryObject();
          this.fs.loadData(true);
        },
        () => {
          this.regfs.isSaveing = false;
        }
      );
    }
  }

  ngOnInit(): void {
  }
}
